import hashlib
from apps.pay.order.dao import OrderDao
import requests
import json
import xmltodict
from apps.common.utils.time import getFormatTime
from apps.common.utils.tools import *
from apps.interface.client.models import Client
from decimal import Decimal
from project.settings import BASE_DIR
from Crypto.Cipher import AES   # pip install pycryptodome

def getSign(params, mch_key):
    '''签名函数，参数为签名的数据和密钥'''
    stringA = ''
    ks = sorted(params.keys())
    # 参数排序
    for k in ks:
        stringA += (k + '=' + str(params[k]) + '&')
    # 拼接商户KEY
    stringSignTemp = stringA + "key=" + mch_key
    # md5加密,也可以用其他方式
    hash_md5 = hashlib.md5(stringSignTemp.encode('utf8'))
    sign = hash_md5.hexdigest().upper()
    return str(sign)

def aes_ecb_pkcs7(body, key):
    """AES-ECB模式解密PKCS7Padding"""
    unpad = lambda s: s[:-ord(s[len(s) - 1:])]
    cipher = AES.new(key.encode('utf8'), AES.MODE_ECB)
    return unpad(cipher.decrypt(body)).decode('utf8')

def returnMoney(params):
    orderId = params.get('orderId')
    order = OrderDao().findOneByOrderId(orderId)
    client_model = Client.objects.get(clientname=params.get('clientname'))
    #设置参数
    realPay = 0
    if client_model.realPay > 0:
        realPay = Decimal(client_model.realPay)
    else:
        realPay = order.realPay
    realPay = int(Decimal(realPay) * 100)
    r_params={}
    r_params["mch_id"] = client_model.mch_id
    r_params["appid"] = client_model.appid
    r_params["nonce_str"] = random_str(32)
    r_params["sign_type"] = "MD5"
    r_params["out_trade_no"] = orderId
    r_params["out_refund_no"] = orderId #str(getFormatTime('%Y%m%d%H%M%S') + random_num(4)),
    r_params['total_fee'] = realPay
    r_params["refund_fee"] = realPay
    r_params["notify_url"] = client_model.baseUrl + client_model.notify_url_return
    
    refundApi = "https://api.mch.weixin.qq.com/secapi/pay/refund"
    r_params["sign"]=getSign(r_params, client_model.mch_key)
    # print('r_params',r_params)
    data = {'root': r_params}

    apiclient_cert = "{}/cert/apiclient_cert.pem".format(BASE_DIR)
    apiclient_key = "{}/cert/apiclient_key.pem".format(BASE_DIR)

    xml = xmltodict.unparse(data)
    res = requests.post(refundApi, cert=(apiclient_cert, apiclient_key), data=xml.encode('utf-8'), headers={'Content-Type': 'text/xml'})
    xmlmsg = xmltodict.parse(res.text)
    # 获取prepay_id
    if xmlmsg['xml']['return_code'] == 'SUCCESS':
        if xmlmsg['xml']['result_code'] == 'SUCCESS':
            # print('r_data', xmlmsg)
            print('result_code', 'SUCCESS')
        else:
            print('return_msg', xmlmsg['xml']['err_code_des'].encode('raw_unicode_escape').decode('utf-8'))
    else:
        print('return_msg', xmlmsg['xml']['return_msg'].encode('raw_unicode_escape').decode('utf-8'))